package com.heatup.apt.api.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import javax.annotation.Resource;

import com.heatup.apt.api.controller.pay.util.PropertiesUtil;
import com.heatup.apt.api.service.CourseListService;
import com.heatup.apt.common.constants.CourseConstants;
import com.heatup.apt.common.constants.CourseConstants.CourseType;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.dao.CourseListMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.ServicePriceMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.dao.user.UserStoreMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.model.api.StoreCampCourseResultModel;
import com.heatup.apt.model.api.store.StoreResultModel;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.api.StoreTeamCourseResultModel;
import com.heatup.apt.model.api.TeamCourseResultModel;
import com.heatup.apt.model.api.course.CourseSecretInfoModel;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 团体课程
 * <P>File name : TeamCourseServiceImpl.java </P>
 *
 * <P>Date : 2016年8月23日 </P>
 */
@Service("courseListService")
public class CourseListServiceImpl implements CourseListService {
	private final static String TIP_MSG= PropertiesUtil.getString("course_tip_msg").trim();
	private final static String PRE_SALE_DATE=PropertiesUtil.getString("course_pre_sale_date").trim();
	private final static Logger logger = LoggerFactory.getLogger(CourseListServiceImpl.class);
	@Resource
	private CourseListMapper courseListMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private OrderInfoMapper orderInfoMapper;
	@Resource
	private ServicePriceMapper servicePriceMapper;

	@Autowired
	private UserStoreMapper userStoreMapper;

	/**
	 * 团体课程
	 *
	 * <P>Date : 2016年8月29日 </P>
	 * @return
	 * @see CourseListService#getTeamCourseList(Map)
	 */

    @Override
    public Map<String, Object> getTeamCourseList(Map<String,Object> parameterMap) {
        logger.info("==============getTeamCourseList start==============");
        logger.info("getTeamCourseList method params is parameterMap : " +parameterMap);
        Map<String, Object> map = new HashMap<>();
        map.put("userLevel", parameterMap.get("userLevel"));
        List<Map<String, Object>> resultList = new ArrayList<>();
        String curdate=(String) parameterMap.get("curdate");
        Integer pageNo= (int) parameterMap.get("pageNo");
        Integer pageSize = (int) parameterMap.get("pageSize");
        Integer storeId = (int) parameterMap.get("storeId");
        UserInfo userInfo =(UserInfo)parameterMap.get("userInfo");
        String longitudeLatitude = (String) parameterMap.get("longitudeLatitude");
        Date currentDate = new Date();
        Date preSaleDate = null;
        try {
            if(PRE_SALE_DATE.equals("")||PRE_SALE_DATE==null){
                preSaleDate = DateUtils.toDate(DateUtils.format(currentDate,  DateUtils.datePattern), DateUtils.datePattern);
            }else{
                preSaleDate = DateUtils.toDate(PRE_SALE_DATE, DateUtils.datePattern);
            }
        } catch (ParseException e) {
            logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage()+"_"+e.getMessage());
        }
        int upcompletedCount = 1;
        upcompletedCount = courseListMapper.getUncompletedTeamCourseCount(parameterMap);
        //如果当前日志传入的为空时，取默认的开始日志。预售日期前前的取预算日期开始的日期，预算日期后，则取当前系统时间
        if("".equals(curdate)){
            if(currentDate.before(preSaleDate)){
                curdate=DateUtils.format(preSaleDate,  DateUtils.datePattern).split("-")[1]+"."+
                        DateUtils.format(preSaleDate,  DateUtils.datePattern).split("-")[2];
            }else{
                /**
                 if(upcompletedCount > 0){
                 curdate=DateUtils.format(new Date(), DateUtils.datePattern).split("-")[1]+"."+
                 DateUtils.format(new Date(), DateUtils.datePattern).split("-")[2];
                 }else{
                 //如果当天课程全部结束，则时间延后一天
                 curdate=DateUtils.format(DateUtils.AddDays(new Date(), 1), DateUtils.datePattern).split("-")[1]+"."+
                 DateUtils.format(DateUtils.AddDays(new Date(), 1), DateUtils.datePattern).split("-")[2];
                 }*/
                curdate=DateUtils.format(new Date(), DateUtils.datePattern).split("-")[1]+"."+
                        DateUtils.format(new Date(), DateUtils.datePattern).split("-")[2];
            }
        }

        for (int i = 0; i < 7; i++)
        {
            Map<String, Object> daylistteamCourseList = new HashMap<>();
            String date  = null;
            //如果当天课程全部结束，则查询时间延后一天
            /**
             if(upcompletedCount > 0){
             date= DateUtils.format(DateUtils.AddDays(new Date(), i), DateUtils.datePattern);
             }else{
             date= DateUtils.format(DateUtils.AddDays(new Date(), i+1), DateUtils.datePattern);
             }*/

            date= DateUtils.format(DateUtils.AddDays(new Date(), i), DateUtils.datePattern);

            if(currentDate.before(DateUtils.AddDays(preSaleDate, 1))){
                date=DateUtils.format(DateUtils.AddDays(preSaleDate, i),  DateUtils.datePattern);
            }

            String dateDay =date.split("-")[1]+"."+date.split("-")[2];
            daylistteamCourseList.put("date", dateDay);
            daylistteamCourseList.put("week", DateUtils.getWeekDay(date));


            Map<String, Object> params = new HashMap<>();
            params.put("status", CourseConstants.CourseStatus.online.getStatus());
            params.put("courseType", CourseType.team_course.getType());
            params.put("date", date);
            params.put("pageNo", pageNo*pageSize);
            params.put("pageSize", pageSize);
            params.put("userId", userInfo.getId());
            if(storeId>0){
                params.put("storeId", storeId);
            }

            if(StringUtils.isNotBlank(longitudeLatitude) && longitudeLatitude.split(",").length == 2){
                params.put("latitude", longitudeLatitude.split(",")[0]);
                params.put("longitude", longitudeLatitude.split(",")[1]);
            }
            int count =0;
            List<Map<Object,Object>> storeList = new ArrayList<Map<Object,Object>>();
            if(dateDay.equals(curdate)){
                logger.info("=====getTeamCourseList getStoreTeamCourseList param is params : "+ params);
                List<StoreTeamCourseResultModel> storeTeamCourseList = courseListMapper.getStoreTeamCourseList(params);
                count = courseListMapper.getStoreTeamCourseListCount(params);
                if (null != storeTeamCourseList && storeTeamCourseList.size() > 0) {
                    for (StoreTeamCourseResultModel storeTeamCourse : storeTeamCourseList) {
                        Map<Object,Object> storeTeamCourseMap = new HashMap<Object,Object>();
                        storeTeamCourseMap.put("store_id", storeTeamCourse.getId());
                        storeTeamCourseMap.put("store_name", storeTeamCourse.getStoreName());
                        storeTeamCourseMap.put("distance", storeTeamCourse.getDistance());
                        storeTeamCourseMap.put("latitude", storeTeamCourse.getLatitude());
                        storeTeamCourseMap.put("longitude", storeTeamCourse.getLongitude());
                        storeTeamCourseMap.put("address", storeTeamCourse.getAddress());
                        storeTeamCourseMap.put("isFave", storeTeamCourse.getIsFave());
                        storeTeamCourseMap.put("pServiceType",storeTeamCourse.getpServiceType());
                        List<TeamCourseResultModel> teamCourseResluts = storeTeamCourse.getTeam_course_list();
                        if (null != teamCourseResluts && teamCourseResluts.size() > 0) {
                            for (TeamCourseResultModel teamCourse : teamCourseResluts) {
                                if (StringUtil.isNotEmpty(teamCourse.getEvalLable())) {
                                    teamCourse.setTags(Arrays.asList(teamCourse.getEvalLable().split("#")));
                                }
                                //课程类型
                                teamCourse.setServiceType(teamCourse.getCourseType());
                                //普通价格
                                teamCourse.setPrice(teamCourse.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                                //会员价格
                                teamCourse.setVipPrice(teamCourse.getVipPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                        }
                        storeTeamCourseMap.put("team_course_list", teamCourseResluts);
                        storeList.add(storeTeamCourseMap);
                    }

                }
            }
            daylistteamCourseList.put("store_list", storeList);
            daylistteamCourseList.put("store_list_count", count);
            resultList.add(daylistteamCourseList);
        }
        if(StringUtils.isBlank(TIP_MSG)){
            map.put("course_tip", "");
        }else{
            map.put("course_tip", TIP_MSG);
        }
        map.put("day_week_list", resultList);
        return map;
    }


	/**
	 * 私教课程
	 *
	 * <P>Date : 2016年8月23日 </P>
	 * @param pageNo
	 * @param pageSize
	 * @param coachId
	 * @param userId
	 * @return
	 * @see CourseListService#getPTCourseList(Integer, Integer, Integer, Integer)
	 */
	@Override
	public Map<String, Object> getPTCourseList(Integer pageNo, Integer pageSize, Integer coachId, Integer userId) {
		if (StringUtil.isEmpty(pageNo)) pageNo = 0;
		if (StringUtil.isEmpty(pageSize)) pageNo = 10;

		Map<String, Object> params = new HashMap<>();
		params.put("pageNo", pageNo*pageSize);
		params.put("pageSize", pageSize);
		params.put("status", CourseConstants.CourseStatus.online.getStatus());
		params.put("courseType", CourseType.private_course.getType());
		if(coachId>0){
			params.put("coachId", coachId);
		}
		params.put("userId", userId);
		List<CourseSecretInfoModel> elements = courseListMapper.getPTCourseList(params);
		List<Integer> ids = orderInfoMapper.queryOrderLimitListByCourseIdAndUserId(userId);
		int secretListSize = 0;

		if (ids != null && ids.size() > 0) {
			secretListSize = ids.size();
			if (elements != null && elements.size() > 0) {
				elements.removeIf(secretInfoModel -> ids.contains(secretInfoModel.getCourseId()));
			}
		}

		if (elements != null && elements.size() > 0) {
			for (CourseSecretInfoModel csModel : elements) {
				if (StringUtil.isNotEmpty(csModel.getEvalLable())) {
					csModel.setTags(Arrays.asList(csModel.getEvalLable().split("#")));
				}
				Map<Object, Object> m = new HashMap<Object, Object>();
				m.put("courseId", csModel.getCourseId());
				m.put("serviceType", CourseType.private_course.getType());
				csModel.setVipPrice(csModel.getVipPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
			}
		}

		Map<String, Object> storeMap = new HashMap<>();
		storeMap.put("coursesecret_list", elements);
		storeMap.put("coursesecret_list_count",  courseListMapper.getPTCourseListCount(params) - secretListSize);

		return storeMap;
		
		
		
		/*maxxiang: 私教列表不要按门店分类了，这段代码先备注先	
		 * 	for (PTCourseResultModel ptCourseResultModel : elements) {
			for(CourseSecretInfoModel csModel: ptCourseResultModel.getCoursesecret_list()){
				if (StringUtil.isNotEmpty(csModel.getEvalLable())) {
					csModel.setTags(Arrays.asList(csModel.getEvalLable().split("#")));
				}
				Map<Object, Object> m = new HashMap<Object, Object>();
				m.put("courseId", csModel.getCourseId());
				m.put("serviceType", CourseType.private_course.getType());
				List<ServicePriceResultModel> servicePrices = servicePriceMapper.queryServicePriceByMap(m);
				if (servicePrices.size()==0){ 
					//maxxiang： 特别注意，如果从价格表取不到课程的价格则表示数据库有错误了，这里要直接返回错误. 要加上 错误信息
					apiResultModel.setData(null);
					return apiResultModel;
				}
				for (ServicePriceResultModel servicePriceResultModel : servicePrices) {				
					//maxxiang 计算出会员价
					csModel.setPrice(servicePriceResultModel.getPrimePrice());
					csModel.setVipPrice(servicePriceResultModel.getPrimePrice().multiply( BigDecimal.valueOf(UserConstants.VipUserDiscount)));
					break; //只会查到一条
				}
				
			} */
	}

	/**
	 * 檬营
	 *
	 * <P>Date : 2016年8月31日 </P>
	 * @param pageIndex 当前页面
	 * @param pageSize 页面大小
	 * @param longitudeLatitude 经纬度 add by blank
	 * @return
	 * @see CourseListService#getCampCourseList(Integer,Integer,String,UserInfo)
	 */
	@Override
	public Map<String, Object> getCampCourseList(Integer pageIndex, Integer pageSize, String longitudeLatitude, UserInfo userInfo) {
		if (StringUtil.isEmpty(pageIndex)) pageIndex = 0;
		if (StringUtil.isEmpty(pageSize)) pageSize = 10;

		Map<String, Object> paramsMap = new HashMap<>();
		if(StringUtils.isNotBlank(longitudeLatitude) && longitudeLatitude.split(",").length == 2){
			paramsMap.put("latitude", longitudeLatitude.split(",")[0]);
			paramsMap.put("longitude", longitudeLatitude.split(",")[1]);
		}

		paramsMap.put("status", CourseConstants.CourseStatus.online.getStatus());
		paramsMap.put("courseType", CourseType.fun_camp.getType());
		paramsMap.put("pageNo", pageIndex * pageSize);
		paramsMap.put("pageSize", pageSize);
		paramsMap.put("userId", userInfo.getId());
		List<StoreCampCourseResultModel> storeList = courseListMapper.getCampCourseList(paramsMap);
		int count = courseListMapper.queryCampCourseCount(paramsMap);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("camp_store_list", storeList);
		resultMap.put("camp_store_list_count", count);
		return resultMap;
	}

	/**
	 * 自助健身
	 *
	 * <P>Date : 2016年8月31日 </P>
	 * @param pageIndex
	 * @param pageSize
	 * @param longitudeLatitude 经纬度 blank
	 * @return
	 * @see CourseListService#getSelfFitnessList(Integer,Integer,String,Integer)
	 */
	@Override
	public Map<String, Object> getSelfFitnessList(Integer pageIndex, Integer pageSize,
												  String longitudeLatitude, Integer userId) {

		Map<String, Object> params = new HashMap<>();
		params.put("pageIndex", pageIndex * pageSize);
		params.put("pageSize", pageSize);
		if(StringUtils.isNotBlank(longitudeLatitude) && longitudeLatitude.split(",").length == 2){
			params.put("latitude", longitudeLatitude.split(",")[0]);
			params.put("longitude", longitudeLatitude.split(",")[1]);
		}
		params.put("userId", userId);
		List<StoreResultModel> elements = courseListMapper.getSelfFitnessList(params);
		Map<String, Object> map = new HashMap<>();

		map.put("list", elements);
		map.put("count", courseListMapper.getSelfFitnessCount());

		return map;
	}

}
